package com.hanxiaozhang.no3algorithm;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2023/3/14
 * @since 1.0.0
 */
public class No9TopK {

    /**
     * 保存多少TOP元素
     */
    public static final Integer TOP_NUM = 10;


    /**
     * 小堆
     */
    private final static PriorityQueue<Long> PRIORITY_QUEUE = new PriorityQueue<>(TOP_NUM);


    public static void main(String[] args) {

        for (int i = 0; i < 1000; i++) {
            Long num = (long) (Math.random() * 10000);
            System.out.println("random member is " + num);
            addToTopKQueue(num, TOP_NUM);
        }
        System.out.println(PRIORITY_QUEUE);

    }


    /**
     * 添加元素到TopKQueue
     *
     * @param target
     * @param topNum
     */
    public static void addToTopKQueue(Long target, Integer topNum) {
        if (PRIORITY_QUEUE.size() < topNum) {
            PRIORITY_QUEUE.add(target);
        } else {
            // 找到堆顶元素的值，即堆中最小值
            Long head = PRIORITY_QUEUE.peek();
            // target大于堆中最小值，弹出堆顶元素，插入target
            if (target > head) {
                PRIORITY_QUEUE.poll();
                PRIORITY_QUEUE.add(target);
            }
        }
    }

}